import requests
import string, time, re, secrets, random
import threading, base64
from bs4 import BeautifulSoup
import urllib3
urllib3.disable_warnings()

# from anticaptchaofficial.hcaptchaproxyless import *

def randomString(string_length):
        input = string.ascii_lowercase + string.digits
        return ''.join(secrets.choice(input) for i in range(string_length))


def genProxy():###EMAILNATOR PROXY

    # geo.iproyal.com:12321:***:*****_session-abuo4jtv_lifetime-30m_streaming-1

    return {'http': 'http://'+proxy,'https': 'http://'+proxy}


class Emailnator:
    def __init__(self, s) -> None:
        self.client = s
        s.proxies = genProxy()
        self.client.get('https://www.emailnator.com/', timeout=6)
        self.cookies = self.client.cookies.get_dict()

        self.client.headers = {
            'authority'      : 'www.emailnator.com',
            'origin'         : 'https://www.emailnator.com',
            'referer'        : 'https://www.emailnator.com/',
            'user-agent'     : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36 Edg/101.0.1722.39',
            'x-xsrf-token'   : self.client.cookies.get("XSRF-TOKEN")[:-3]+"=",
        }
        
        self.email = None
        
    def get_mail(self):
        response = self.client.post('https://www.emailnator.com/generate-email',json = {
            'email': [
                # 'domain',
                # 'plusGmail',
                'dotGmail',
            ]
        })
        
        self.email = response.json()["email"][0]
        # print(self.email)
        return self.email
    
    def get_message(self):
        print("waiting for code...")
        # self.email = "p.a.ris.low.ery18.6@gmail.com"
        
        while True:
            mail_token = self.client.post('https://www.emailnator.com/message-list', 
                json   = {'email': self.email})
            
            messageData = mail_token.json()["messageData"]
            messageID = ""

            for i in messageData:
                if "==" not in i['messageID']:
                    continue
                messageID = i['messageID'] 
            if messageID != "":
                break
            time.sleep(2)
        
        mail_context =  self.client.post('https://www.emailnator.com/message-list', json = {
            'email'    : self.email,
            'messageID': messageID,
        })
        
        return mail_context.text

# g = Emailnator()
# print(g.get_mail())
# print(g.get_message())
# print(Gmailnator.receiveInbox())

def action():
    s = requests.Session()
    ########s.verify = False
    


    g = Emailnator(s)
    email = g.get_mail()
    
    # print(email)
    
    s.headers = {
        'origin': 'https://hebits.net',
        'content-type': 'application/x-www-form-urlencoded',
        'user-agent': 'Mozilla/5.0 (windows 11 x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'referer': 'https://hebits.net/register.php',
    }
    # username =      secrets.choice(usernames_bulk)+randomString(random.randint(1,2))
    username =      randomString(5)
    # password = randomStringExtra(random.randint(10,14))
    password = 'dfdfJDFDF!@!!!12'



    def new_captcha():
        r = s.get("https://hebits.net/register.php")
        print(r.text)
        soup = BeautifulSoup(r.text, features="html.parser")
        # image = soup.find('img')['src']
        # print(image)
        captchas = soup.find_all('input', attrs={'name': 'captcha'})
        captcha_captcha = soup.find('input', {'name': 'image'})['value']

        ways = []
        for x in captchas:
            ways.append(x['value'])

    def do_post():
        data = {
            'email': email,
            'username': username,
            'new_pass_1': password,
            'new_pass_2': password,

            'readrules': '1',
            'readwiki': '1',
            'agereq': '1',

            'image': captcha_captcha,
            'captcha': secrets.choice(ways),

            'submit': 'הרשמה!',
        }

        r = s.post('https://hebits.net/register.php', headers=headers, data=data)
        print(r.text)
    new_captcha()
    do_post()

    while True:#!FAULTY
        if 'name="captcha' not in r.text:
            if "אימייל נשלח לכתובת המייל שסיפקת. לאחר שתאושר כתובת המייל, יהיה ניתן להתחבר לחשבון." in r.text:
                # print(r.text)

                if "\u05D5\u05D1\u05EA \u05D4\u05DE\u05D9\u05D9\u05DC \u05E9\u05E1\u05D9\u05E4\u05E7\u05EA" in r.text:
                    receiveEmail = g.get_message()
                    match = re.findall(r'(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?', receiveEmail)[0]

                    url = f"{match[0]}://{match[1]}/{match[2]}"
                    
                    r = s.get(url)
                    if "החשבון שלך נוצר" in r.text:
                        print("MADE!")
                        main.stats_AmountAccountsMade += 1
                        with open('output2.txt', 'a') as f:
                            f.write(f"{username}:{password}\n")
            break
        if 'name="captcha' not in r.text:
            new_captcha()
            do_post()


class mainBot():
    def action():
        while True:
            try:
                action()
            except:
                raise

class mainDoingThreads():
    stats_AmountAccountsMade = int(0)
    
    def STATS(self):
        while True:
            try:
                print(f"[#] Accounts made {main.stats_AmountAccountsMade}")
                time.sleep(5)
            except:
                raise

    def DoThreads(self,threads):
        for x_thread in range(threads):
            threading.Thread(target=mainBot.action).start()
        threading.Thread(target=main.STATS).start()

    
    def Main(self):
        threads_atonce=int( str(input("How many threads would you like? (each thread has x5 subthreads of short): ")) )
        self.DoThreads(threads_atonce)



main = mainDoingThreads()
main.Main()


#/**
#import socket

#$$print("/etc/hosts content:\n")
#with open('/etc/hosts', 'r') as fin:
#    print(fin.read())
#print("\nDNS Resolution: ={}".format(socket.gethostbyname('hebits.net')))

# g = Emailnator()
# email = g.email
# print(email)
# print(g.get_verification_link(email))

# print(email)**/